package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartInfoService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.model.ProductSku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CartInfoServiceImpl implements ICartInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Override
    public void addToCart(Long skuId, Integer num) {
        //判断购物车中是否有商品
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        String field = skuId.toString();
        Boolean exists = redisTemplate.opsForHash().hasKey(cartKey,field);
        //如果商品存在，则更新
        if (exists){
            CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey,field);
            Integer skuNum = cartInfo.getSkuNum();
            cartInfo.setSkuNum( skuNum + num > 99 ? 99: skuNum + num);
            cartInfo.setUpdateTime(new Date());
            redisTemplate.opsForHash().put(cartKey,field,cartInfo);
        }else {
            Long size = redisTemplate.opsForHash().size(cartKey);
            if (size > 50){
                throw new RuntimeException("最多只能加入50个商品");
            }

            R<ProductSku> r = remoteProductService.gettProductsku(skuId, SecurityConstants.INNER);
            if (r.getCode() != 200){
                throw new ServiceException("远程调用商品服务失败，原因" + r.getMsg());
            }
            ProductSku productSku = r.getData();
            //创建购物车对象
            CartInfo cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(productSku.getId());
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(num > 99 ? 99 : num);
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setCreateTime(new Date());

            //4.2 将购物车商品存入Redis
            redisTemplate.opsForHash().put(cartKey,field, cartInfo);


        }

    }


    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }
}
